﻿using FreeSql;
using FreeSql.DataAnnotations;
using System;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;

namespace shop.Model
{

    /// <summary> 数据库 </summary>
    public static class DB
    {
        /// <summary> 默认库 </summary>
        public static readonly string DefaultCatalog = "boya";

        /// <summary> 数据库链接字符串 </summary>
        static string CONN = "Data Source={0};Initial Catalog={1};User ID=sa;pwd=Shijian2017;Connect Timeout=30;Connection Timeout=30;TrustServerCertificate=True;";



        /// <summary> 数据库对象 </summary>
        public static IFreeSql FSql { set; get; }


        /// <summary> 初始化 </summary>
        public static bool Init(string servAddr, bool useSqlServer= true)
        {

            var con = string.Format(CONN, servAddr, DefaultCatalog);
            if (true)
            {
                //创建管理数据库
                var builder = new FreeSql.FreeSqlBuilder()
                    .UseConnectionString(FreeSql.DataType.SqlServer, con)
#if DEBUG
                    .UseAutoSyncStructure(true) //自动同步实体结构【开发环境必备】，FreeSql不会扫描程序集，只有CRUD时才会生成表。
                    .UseMonitorCommand(cmd => Console.WriteLine("FreeSql: "+cmd.CommandText))  //监控数据库命令对象
#endif
                    //.UseMonitorCommand(cmd => cmd.CommandTimeout = 300) // 设置超时时间 5 分钟
            ;

                FSql = builder.Build(); //请务必定义成 Singleton 单例模式

                //自定义特性
                FSql.Aop.ConfigEntityProperty += (s, e) =>
                {
                    var attr = e.Property.GetCustomAttributes(typeof(VarCharAttribute), false).FirstOrDefault() as VarCharAttribute;
                    if (attr != null)
                        e.ModifyResult.DbType = attr.ToString(FSql);
                };
            }
          

            return true;
        }


    }



}
